package admin_v1

import (
	"context"
	"errors"
	"gf-xb-api/internal/consts"
	"gf-xb-api/internal/dao"
	"gf-xb-api/internal/model/dto"
	"gf-xb-api/internal/model/dv"
	"gf-xb-api/internal/model/entity"
	"gf-xb-api/internal/service"
	"gf-xb-api/utility/xpointer"
	"gf-xb-api/utility/xstr"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"golang.org/x/crypto/bcrypt"
)

func (s *sAdmin) Create(ctx context.Context, in dv.SysAdminCreateInput) (err error) {

	// 密码 至少一位大写字母、一位小写字母、一位数字和一位特殊字符（@、_）,且长度在8-30位
	if !xstr.IsValidPassword(in.Password) {
		return errors.New(consts.INVALID_PASSWORD)
	}

	count, err := g.DB().Model(entity.SysUser{}).Where(dao.SysUser.Columns().IsSuperadmin, 1).Count()
	if err != nil {
		return err
	}

	if count > 0 {
		return errors.New("新建管理员失败：用户已存在")
	}

	var data = &entity.SysUser{}

	data.Username = in.Username
	data.Uuid = xstr.GetUUID()

	passwordHash, err := bcrypt.GenerateFromPassword([]byte(in.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	data.PasswordHash = string(passwordHash)
	data.IsSuperadmin = xpointer.GetPointer(1)
	data.Status = uint(consts.USER_STATUS_ACTIVE)

	err = dao.SysUser.Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
		user, err := dao.SysUser.Ctx(ctx).Insert(data)
		if err != nil {
			return errors.New("保存失败：sql出错！")
		}

		userId, err := user.LastInsertId()
		if err != nil {
			return err
		}

		roleIds := []uint{1}

		err = service.UserRole().Create(ctx, &dto.CreateUserRoleInput{
			UserId:  uint(userId),
			RoleIds: roleIds,
		})

		if err != nil {
			return err
		}

		return nil
	})

	return err
}
